package com.project.code.service.impl;

import com.project.code.config.ConfigUtils;
import com.project.code.domain.Column;
import com.project.code.domain.Table;
import com.project.code.mapper.GenerateMapper;
import com.project.code.service.IGenerateService;
import com.project.code.util.GenUtils;
import com.project.code.util.VelocityInitializer;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

/**
 * @author lipeng
 */
@Service
@Slf4j
public class GenerateServiceImpl implements IGenerateService {

    @Autowired
    private GenerateMapper genMapper;

    /**
     * 批量生成代码
     *
     * @param tableNames 表数组
     * @return 数据
     */
    @Override
    public void generatorCode(String[] tableNames) {
        try {
            File file = new File(ConfigUtils.getFilePath() + "generator.zip");
            file.deleteOnExit();
            file.createNewFile();
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            ZipOutputStream zip = new ZipOutputStream(fileOutputStream);
            for (String tableName : tableNames) {
                log.info("start table :{}", tableName);
                // 查询表信息
                Table table = genMapper.selectTableByName(tableName);
                // 查询列信息
                List<Column> columns = genMapper.selectTableColumnsByName(tableName);
                // 生成代码
                generatorCode(table, columns, zip);
                log.info("end table :{}", tableName);
            }
            IOUtils.closeQuietly(zip);
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * 生成代码
     */
    public void generatorCode(Table table, List<Column> columns, ZipOutputStream zip) {
        // 表名转换成Java属性名
        String className = GenUtils.tableToJava(table.getTableName());
        table.setClassName(className);
        table.setClassname(StringUtils.uncapitalize(className));
        // 列信息
        table.setColumns(GenUtils.transColums(columns));
        // 设置主键
        table.setPrimaryKey(table.getColumnsLast());

        VelocityInitializer.initVelocity();

        String packageName = ConfigUtils.getPackageName();
        String moduleName = GenUtils.getModuleName(packageName);

        VelocityContext context = GenUtils.getVelocityContext(table);

        // 获取模板列表
        List<String> templates = GenUtils.getTemplates();
        for (String template : templates) {
            // 渲染模板
            StringWriter sw = new StringWriter();
            Template tpl = Velocity.getTemplate(template, "UTF-8");
            tpl.merge(context, sw);
            try {
                // 添加到zip
                zip.putNextEntry(new ZipEntry(GenUtils.getFileName(template, table, moduleName)));
                IOUtils.write(sw.toString(), zip, "UTF-8");
                IOUtils.closeQuietly(sw);
                zip.closeEntry();
            } catch (IOException e) {
                log.error("渲染模板失败，表名：" + table.getTableName(), e);
            }
        }
    }
}
